import 'package:dio/dio.dart' as dio show Response;
import 'package:get/get.dart';

/// 基础响应类
class BaseResponse<T> {
  /// 响应码
  final int code;

  /// 响应消息
  final String msg;

  /// 单个对象数据
  final T? data;

  /// 列表数据
  final List<T>? list;

  /// 列表total
  final int? total;

  /// 原始响应数据
  final Map<String, dynamic>? rawData;

  /// 是否成功 (2xx 都认为是成功)
  bool get isSuccess => code >= 200 && code < 300;

  /// 是否有数据
  bool get hasData => data != null || (list?.isNotEmpty ?? false);

  BaseResponse({
    required this.code,
    required this.msg,
    this.data,
    this.list,
    this.total,
    this.rawData,
  });

  /// 从JSON映射创建BaseResponse对象
  factory BaseResponse.fromJson(Map<String, dynamic> json, T Function(Map<String, dynamic>) fromJson) {
    // 解析data字段
    T? parsedData;
    if (json['data'] != null) {
      if (json['data'] is Map<String, dynamic>) {
        try {
          parsedData = fromJson(json['data'] as Map<String, dynamic>);
        } catch (e) {
          print('Error parsing data: $e');
        }
      } else if (json['data'] is List) {
        // 如果data是列表，尝试解析第一个元素
        final dataList = json['data'] as List;
        if (dataList.isNotEmpty && dataList.first is Map<String, dynamic>) {
          try {
            parsedData = fromJson(dataList.first as Map<String, dynamic>);
          } catch (e) {
            print('Error parsing first item in data list: $e');
          }
        }
      }
    }

    // 解析list字段
    List<T>? parsedList;
    if (json['list'] != null && json['list'] is List) {
      try {
        parsedList = (json['list'] as List).where((item) => item is Map<String, dynamic>).map((item) => fromJson(item as Map<String, dynamic>)).toList();
      } catch (e) {
        print('Error parsing list: $e');
      }
    } else if (json['data'] is List) {
      // 如果data字段是列表，也尝试解析
      try {
        parsedList = (json['data'] as List).where((item) => item is Map<String, dynamic>).map((item) => fromJson(item as Map<String, dynamic>)).toList();
      } catch (e) {
        print('Error parsing data as list: $e');
      }
    }

    return BaseResponse<T>(
      code: json['code'] as int? ?? 200, // 默认成功
      msg: json['message'] as String? ?? json['msg'] as String? ?? '',
      data: parsedData,
      list: parsedList,
      total: json['total'] as int? ?? parsedList?.length,
      rawData: json,
    );
  }

  /// 将BaseResponse对象转换为JSON映射
  Map<String, dynamic> toJson(Map<String, dynamic> Function(T) toJson) {
    final Map<String, dynamic> result = {
      'code': code,
      'msg': msg,
    };

    if (data != null) {
      result['data'] = toJson(data!);
    }

    if (list != null) {
      result['list'] = list!.map((item) => toJson(item)).toList();
    }

    if (total != null) {
      result['total'] = total;
    }

    return result;
  }

  /// 从响应创建
  factory BaseResponse.fromResponse(dio.Response response) {
    final statusCode = response.statusCode ?? 200;
    final data = response.data;

    if (data is Map<String, dynamic>) {
      return BaseResponse(
        code: data['code'] ?? statusCode,
        msg: data['msg'] ?? data['message'] ?? '',
        data: data['data'],
        list: data['list'],
        total: data['total'],
        rawData: data,
      );
    }

    // 处理非Map类型的响应
    if (statusCode >= 200 && statusCode < 300) {
      return BaseResponse(
        code: statusCode,
        msg: 'success',
        data: data,
        rawData: {'data': data},
      );
    }

    return BaseResponse(
      code: statusCode,
      msg: 'response_format_error'.tr,
      rawData: data is Map ? data as Map<String, dynamic> : {'data': data},
    );
  }
}
